package com.boarsoft.gateway.server.service;

import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsOperations;
import org.springframework.stereotype.Service;

import com.boarsoft.demo.gateway.server.entity.PocAccountReverseRequest;
import com.boarsoft.demo.gateway.server.entity.PocAccountTransferRequest;
import com.boarsoft.demo.gateway.server.service.PocAccountTransferService;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Service("accountTransferServ")
public class PocAccountTransferServiceImpl implements PocAccountTransferService {
	private static final Logger log = LoggerFactory.getLogger(PocAccountTransferServiceImpl.class);

	// @Autowired
	// private JmsTemplate jms;
	@Autowired
	protected JmsOperations jms;

	@Autowired
	private Configuration config;

	@Override
	public boolean transfer(PocAccountTransferRequest transferRequest) {
		log.info("开始转账....");
		String xml = getTemplateContent("transfer_request.ftl", transferRequest);
		if (StringUtils.isBlank(xml)) {
			return false;
		}
		log.info("给MQ发送转账请求的XML文件");
		System.out.println(xml);
		jms.convertAndSend("POC1.PROVIDER.IN", xml);
		return true;

	}

	@Override
	public boolean reverse(PocAccountReverseRequest reverseRequest) {
		log.info("开始冲正...");
		String xml = getTemplateContent("reverse_request.ftl", reverseRequest);
		if (StringUtils.isBlank(xml)) {
			return false;
		}
		log.info("给MQ发送冲正请求的XML文件");
		System.out.println(xml);
		jms.convertAndSend("POC2.PROVIDER.IN", xml);
		return true;
	}

	private String getTemplateContent(String templateName, Object bean) {
		try {
			Map<String, String> dataModel = BeanUtils.describe(bean);
			Template template = config.getTemplate(templateName);
			StringWriter sw = new StringWriter();
			template.process(dataModel, sw);
			return sw.toString();
		} catch (Exception e) {
			log.error("生成报文失败", e);
			return null;
		}

	}

}
